package com.sfac.javaSpringBoot.filter;

import com.sfac.javaSpringBoot.listener.LogDestroyListener;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter(filterName ="paramFilter",value = {"/*"})
public class ParamFilter implements Filter {
    private final static Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("====do filter====");
        HttpServletRequest re=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;

        HttpServletRequestWrapper wrapper=new HttpServletRequestWrapper(re){
            @Override
            public String getParameter(String name) {
                String value=super.getParameter(name);
                if (StringUtils.isNotBlank(value)){
                    value=value.replaceAll("fuck","***");
                }
                return value;
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values=super.getParameterValues(name);
                //循环
                return  Arrays.asList(values).stream()
                        .map(item-> item.replaceAll("fuck","***"))
                        .toArray(String[] ::new );
            }
        };

        chain.doFilter(wrapper,resp);

    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("====init filter====");

    }

    @Override
    public void destroy() {
        LOGGER.debug("====destroy filter====");


    }
}
